package com.ulife.order.service.domain;

import com.ulife.base.entities.order.*;
import com.ulife.base.logics.order.CpsTraceLogic;
import com.ulife.base.logics.order.SaleOrderItemLogic;
import com.ulife.base.logics.order.SaleOrderLogic;
import com.ulife.common.utils.lang.DateUtils;
import com.ulife.order.api.response.*;
import com.ulife.order.service.dto.YqfTraceDTO;
import com.ulife.order.service.enumeration.SaleOrderPayStatus;
import com.ulife.order.service.util.JsonUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Ulife on 2016/4/14.
 */
@Service
public class Yqf {

    @Resource
    Order order;

    @Resource
    SaleOrderLogic saleOrderLogic;

    @Resource
    CpsTraceLogic cpsTraceLogic;

    @Resource
    SaleOrderItemLogic saleOrderItemLogic;

    /*
    * 根据订单号，获取指定source|cid的亿起发订单
    * source:emar|cid
    * */
    public YqfOrderListInfo get(SaleOrderInfo saleOrderInfo, String source) {
        YqfOrderListInfo rtn = new YqfOrderListInfo();
        if (saleOrderInfo == null || saleOrderInfo.getItems() == null || saleOrderInfo.getItems().size() == 0)
            return rtn;

        CpsTraceCriteria cpsTraceCriteria = new CpsTraceCriteria();
        cpsTraceCriteria.createCriteria().andSoNoEqualTo(saleOrderInfo.getSaleNo());
        List<CpsTrace> cpsTraces = cpsTraceLogic.list(cpsTraceCriteria);
        if (cpsTraces == null || cpsTraces.size() == 0) return rtn;
        CpsTrace trace = cpsTraces.get(0);// todo if多家cps
        YqfTraceDTO dto = JsonUtils.json2Obj(trace.getJsonValue(), YqfTraceDTO.class);
        if (dto == null) return rtn;
        if (!source.equalsIgnoreCase(dto.getSource() + "|" + dto.getCid())) return rtn;//验证source和cid

        List<YqfOrderInfo> list = new ArrayList<>();
        rtn.setOrders(list);

        YqfOrderInfo info = new YqfOrderInfo();
        list.add(info);

        info.setOrderNo(saleOrderInfo.saleNo);
        info.setCampaignId(dto.getCid());
//        info.setFare(saleOrderInfo.getShipFee() - saleOrderInfo.getShipFeeCouponDiscount() - saleOrderInfo.getShipFeeDiscount());
        info.setFeedback(dto.getWi());
        info.setOrderStatus(String.valueOf(saleOrderInfo.getStatus()));//todo 中文？
        info.setOrderTime(DateUtils.formatDateTime(new Date(saleOrderInfo.getOrderTime())));
        info.setPaymentStatus(String.valueOf(saleOrderInfo.getPayStatus()));
        info.setPaymentType(saleOrderInfo.getPayType());

        List<YqfOrderItemInfo> products = new ArrayList<>();
        info.setProducts(products);
        double subAmount = saleOrderInfo.getSubAmount();
        double promotionAmount = saleOrderInfo.getProductCouponDiscount() + saleOrderInfo.getPromotionDiscount();
        double promotionRate = 1 - promotionAmount / subAmount;
        for (ItemInfo itemInfo : saleOrderInfo.getItems()) {
            double price = itemInfo.getUnitPrice() * promotionRate;
            BigDecimal temp = new BigDecimal(price);
            price = temp.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();//保留2位小数


            YqfOrderItemInfo yqfOrderItemInfo = new YqfOrderItemInfo();
            yqfOrderItemInfo.setAmount(itemInfo.getQuantity());
            yqfOrderItemInfo.category = "";
            yqfOrderItemInfo.commissionType = "";
            yqfOrderItemInfo.setName(itemInfo.getItemTitle());
            yqfOrderItemInfo.setPrice(price);
            yqfOrderItemInfo.setProductNo(String.valueOf(itemInfo.getItemId()));

            products.add(yqfOrderItemInfo);
        }
        return rtn;
    }

    /*
    * 根据下单时间范围获取订单列表
    * */
    public YqfOrderListInfo listByOrderTime(long start, long end, String source) {
        return list(start, end, 0, 0, source);
    }

    /*
    * 根据订单更新时间范围获取订单列表
    * */
    public YqfOrderListInfo listByUpdateTime(long start, long end, String source) {
        return list(0, 0, start, end, source);
    }

    /*
    *  根据下单、更新时间范围获取订单列表
    * */
    private YqfOrderListInfo list(long orderStart, long orderEnd, long updateStart, long updateEnd, String source) {
        YqfOrderListInfo rtn = new YqfOrderListInfo();
        if ((orderStart == 0 || orderEnd == 0) && (updateStart == 0 || updateEnd == 0)) return rtn;

        SaleOrderCriteria saleOrderCriteria = new SaleOrderCriteria();
        if (orderStart > 0 && orderEnd > 0) {
            saleOrderCriteria.createCriteria().andSourceEqualTo(source).andOrderTimeBetween(new Date(orderStart), new Date(orderEnd));
        } else {
            saleOrderCriteria.createCriteria().andSourceEqualTo(source).andModifiedTimeBetween(new Date(updateStart), new Date(updateEnd));
        }
        List<SaleOrder> saleOrders = saleOrderLogic.list(saleOrderCriteria);
        if (saleOrders == null || saleOrders.size() == 0) return rtn;
        List<YqfOrderInfo> list = new ArrayList<>();
        rtn.setOrders(list);
        for (SaleOrder saleOrder : saleOrders) {
            SaleOrderInfo orderInfo = order.orderInfoMapping(saleOrder);
            orderInfo.setItems(new ArrayList<ItemInfo>());
            List<ItemInfo> itemInfoList = getOrderItemInfoList(saleOrder.getSaleNo());
            for (ItemInfo itemInfo : itemInfoList) {
                orderInfo.getItems().add(itemInfo);
            }
            List<YqfOrderInfo> yqfOrderInfoList = get(orderInfo, source).getOrders();
            if (yqfOrderInfoList == null || yqfOrderInfoList.size() == 0) continue;
            list.add(yqfOrderInfoList.get(0));
        }
        return rtn;
    }

    /**
     * 根据订单号获取商品明细
     *
     * @param sale_no
     * @return
     */
    private List<ItemInfo> getOrderItemInfoList(String sale_no) {
        List<ItemInfo> itemInfoList = new ArrayList<ItemInfo>();

        List<SaleOrderItem> saleOrderItemList = getOrderItemList(sale_no);
        if (saleOrderItemList == null || saleOrderItemList.size() == 0) {
            return itemInfoList;
        }

        if (saleOrderItemList.size() > 0) {
            for (SaleOrderItem saleOrderItem : saleOrderItemList) {
                ItemInfo itemInfo = new ItemInfo();
                itemInfo.setImgUrl(saleOrderItem.getImgUrl());  //* 图片地址还要取
                itemInfo.setItemId(saleOrderItem.getItemId());
                itemInfo.setQuantity(saleOrderItem.getQuantity());
                itemInfo.setItemTitle(saleOrderItem.getItemTitle());
                itemInfo.setWeight(saleOrderItem.getWeight().doubleValue());
                itemInfo.setUnitPrice(saleOrderItem.getUnitPrice().doubleValue());
                itemInfo.setItemForm(saleOrderItem.getItemForm());
                itemInfoList.add(itemInfo);
            }
        }
        return itemInfoList;
    }

    /**
     * 根据订单号获取商品信息
     *
     * @param sale_no
     * @return
     */
    private List<SaleOrderItem> getOrderItemList(String sale_no) {
        SaleOrderItemCriteria saleOrderItemCriteria = new SaleOrderItemCriteria();
        saleOrderItemCriteria.createCriteria().andSoNoEqualTo(sale_no);
        return saleOrderItemLogic.list(saleOrderItemCriteria);
    }


}
